<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.keyword" placeholder="关键字"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="search">查询</el-button>
                </el-form-item>
                <!--<el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>-->
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="petAcquisitionOrders" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="60">
            </el-table-column>
            <el-table-column type="index" width="30">
            </el-table-column>
            <el-table-column prop="digest" label="摘要" width="230" sortable>
            </el-table-column>
            <el-table-column prop="orderSn" label="订单号" width="150" sortable>
            </el-table-column>
            <el-table-column prop="price" label="价格" width="100" sortable>
            </el-table-column>
            <el-table-column prop="lastConfirmTime" label="最后确认时间" width="170" sortable>
            </el-table-column>
            <el-table-column prop="state" label="状态" width="140" sortable>
                <template scope="scope">
                    <span style="color: red" v-if="scope.row.state ==0">待支付</span>
                    <span style="color: green" v-else-if="scope.row.state ==1">已完成</span>
                    <span style="color: gray" v-else>未知</span>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template scope="scope">
                    <el-button size="small" @click="info(scope.$index, scope.row)">详情</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <!--<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>-->
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                           :page-size="pageSize"
                           :total="total"
                           :current-page="page"
                           style="float:right;">
            </el-pagination>
        </el-col>

        <!--新增或编辑界面
           :rules=  申明校验规则
           ref= 绑定当前表当 取一个别名

        -->
        <el-dialog title="新增/编辑" :visible.sync="petAcquisitionOrderFormVisible" :close-on-click-modal="false">
            <el-form :model="petAcquisitionOrderForm" label-width="80px" :rules="petAcquisitionOrderFormRules" ref="petAcquisitionOrderForm">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="petAcquisitionOrderForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="编码" prop="sn">
                    <el-input v-model="petAcquisitionOrderForm.sn" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="state">
                    <el-radio-group v-model="petAcquisitionOrderForm.state">
                        <el-radio class="radio" :label="0">正常</el-radio>
                        <el-radio class="radio" :label="-1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="管理员" prop="manager">
                    <!--
                    :key= 选中ID
                    :label= 选中后，窗体中显示的值
                    :value 最终绑定给model层的数据（注意：如果value要绑定对象，那么必须加上：value-key="id"）
                    -->
                    <el-select v-model="petAcquisitionOrderForm.manager" value-key="id" placeholder="请选择">
                        <el-option
                                v-for="item in employees"
                                :key="item.id"
                                :label="item.username"
                                :value="item">
                            <span style="float: left">{{ item.username }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="父领养订单" prop="parent">
                    <!--
                      :options:双向绑定data层数据
                      value:选中后传递给后端的值
                      label：选中显示到窗体中的值
                    -->
                    <el-cascader v-model="petAcquisitionOrderForm.parent"
                                 :options="deptTree"
                                 :props="{
							   checkStrictly: true,
							    value:'id',
								label:'name'
							    }"
                                 clearable></el-cascader>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="petAcquisitionOrderFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="save" :loading="petAcquisitionOrderLoading">提交</el-button>
            </div>
        </el-dialog>

        <el-dialog title="订单详情" :visible.sync="petAcquisitionOrderInfoVisible" :close-on-click-modal="false">
            <el-form :model="petAcquisitionOrderInfo" label-width="120px" ref="petAcquisitionOrderInfo">
                <el-form-item label="摘要" prop="digest">
                    <el-input readonly="readonly" v-model="petAcquisitionOrderInfo.digest" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="订单号" prop="orderSn">
                    <el-input v-model="petAcquisitionOrderInfo.orderSn" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input v-model="petAcquisitionOrderInfo.price" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="state">
                    <template scope="scope">
                        <span style="color: red" v-if="petAcquisitionOrderInfo.state==0">待支付</span>
                        <span style="color: green" v-else-if="petAcquisitionOrderInfo.state==1">已完成</span>
                        <span style="color: gray" v-else>未知</span>
                    </template>
                </el-form-item>
                <el-form-item label="最后确认时间" prop="lastConfirmTime">
                    <el-input v-model="petAcquisitionOrderInfo.lastConfirmTime" auto-complete="off"></el-input>
                </el-form-item>

                <el-form-item label="宠物名称" prop="manager">
                    <el-input readonly="readonly" v-model="petAcquisitionOrderInfo.pet.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="领养人" prop="parent">
                    <el-input readonly="readonly" v-model="petAcquisitionOrderInfo.user.username" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="门店" prop="parent">
                    <el-input readonly="readonly" v-model="petAcquisitionOrderInfo.shop.name" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="petAcquisitionOrderInfoVisible = false">取消</el-button>
            </div>
        </el-dialog>

    </section>
</template>

<script>
    export default {
        data() {
            return {
                filters: {
                    keyword: ''
                },
                petAcquisitionOrders: [],
                total: 0,
                pageSize:10,
                page: 1,
                listLoading: false,
                sels: [],//列表选中行

                petAcquisitionOrderInfoVisible: false,//订单详情

                petAcquisitionOrderFormVisible: false,//新增/编辑界面是否显示
                petAcquisitionOrderLoading: false,//忙等框
                petAcquisitionOrderFormRules: {//申明校验规则
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }

                    ],
                    sn: [
                        { required: true, message: '请输编号', trigger: 'blur' }
                    ]

                },

                petAcquisitionOrderInfo: {
                    digest: '',
                    state: '',
                    price: 0,
                    orderSn: null,
                    paySn: null,
                    lastPayTime:'',
                    lastConfirmTime: '',
                    pet: {},
                    user: {},
                    shop: {}
                },

                //编辑界面数据
                petAcquisitionOrderForm: {
                    id: null,
                    name: '',
                    sn: '',
                    state: 0,
                    manager: null,
                    parent: null
                },
                employees:[],//页面初始化的时候没有管理员列表
                deptTree:[]//领养订单树集合

            }
        },
        methods: {
            search(){//点击查询按钮的时候，需要定位到第一页
                this.page = 1;
                this.getPetAcquisitionOrders();

            },
            //状态显示转换
            /*formatSex: function (row, column) {
                return row.state == 0 ? '正常' : row.state == -1 ? '禁用' : '未知';
            },*/
            handleCurrentChange(val) {
                this.page = val;
                this.getPetAcquisitionOrders();
            },
            //获取领养订单列表
            getPetAcquisitionOrders() {
                let para = {
                    currentPage: this.page,
                    pageSize: this.pageSize,
                    keyword: this.filters.keyword
                };
                this.listLoading = true;//开启忙等框

                /*发送axios请求，从后端拿数据*/
                this.$http.post("/petAcquisitionOrder/admin",para)
                    .then(result=>{
                        console.log(result.data.rows);
                        this.total = result.data.total;
                        this.petAcquisitionOrders = result.data.rows;
                        this.listLoading = false;//关闭忙等框
                    })
                    .catch(result=>{
                        this.$message({
                            message: '系统异常',
                            type: 'error'
                        });
                    })
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '温馨提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    this.$http.delete("/petAcquisitionOrder/"+row.id)
                        .then(result=>{
                            result = result.data;
                            if(result.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.page = 1;//如果删除成功，定位到第一页
                            }else{
                                this.$message({
                                    message: '删除失败'+result.message,
                                    type: 'error'
                                });
                            }
                            this.getPetAcquisitionOrders();//重新刷新列表
                        })
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.petAcquisitionOrderFormVisible = true;//显示编辑窗口
                //Object.assign 克隆
                this.petAcquisitionOrderForm = Object.assign({}, row);//回显数据
                //假装回显
                //this.petAcquisitionOrderForm.parent = [1,12];
                let dirPath = row.dirPath; // /2/5/11
                if(dirPath){
                    let tmp = [];
                    if(dirPath){
                        let dirPaths =  dirPath.trim().split("/"); //['','2','5','11']
                        for(let i=1;i<dirPaths.length-1;i++){
                            tmp[i-1] = parseInt(dirPaths[i]);
                        }
                    }

                    this.petAcquisitionOrderForm.parent = tmp; //根据dirpath构造数组
                }
            },
            //显示新增界面
            handleAdd: function () {
                this.petAcquisitionOrderFormVisible = true;//显示新增弹出框
                this.petAcquisitionOrderForm={
                    id: null,
                    name: '',
                    sn: '',
                    state: 0,
                    manager: null,
                    parent: null
                };
            },
            //编辑
            save: function () {
                this.$refs.petAcquisitionOrderForm.validate((valid) => {//在一次触发表单校验（理解）
                    if (valid) {
                        this.$confirm('确认提交吗？', '温馨提示', {}).then(() => {
                            this.petAcquisitionOrderLoading = true;//开启忙等框
                            //NProgress.start();
                            //预处理格式  [1]  [1,12]   ==>parent:{id:12}
                            let para = Object.assign({}, this.petAcquisitionOrderForm);
                            if(para.parent){//修改的时候有坑
                                if(para.parent.length == 0){
                                    para.parent=null;
                                }else{
                                    //从表单复制对象中得到parent
                                    let parentArrey = para.parent;//[1,12]
                                    //将parent数组的最后一个值拿出来（最后一个值才是我们选中的父领养订单）
                                    let lastDeptId = parentArrey[parentArrey.length -1];//我当前选中的领养订单ID
                                    //重新将parent属性赋值成 json对象
                                    para.parent ={"id":lastDeptId};
                                }
                            }
                            this.$http.put("/petAcquisitionOrder",para)
                                .then(result=>{
                                    result = result.data;
                                    this.petAcquisitionOrderLoading = false;//关闭忙等框
                                    if(result.success){
                                        this.$message({
                                            message: "操作成功！",//直接提示后端错误就可以了
                                            type: 'success'
                                        });
                                        this.petAcquisitionOrderFormVisible = false;//关闭弹出框
                                        this.page = 1;//定位到第一页
                                        this.getPetAcquisitionOrders();
                                    }else{
                                        this.$message({
                                            message: result.message,//直接提示后端错误就可以了
                                            type: 'error'
                                        });
                                    }
                                })
                                .catch(result=>{
                                    this.$message({
                                        message: '系统错误',
                                        type: 'error'
                                    });
                                    this.petAcquisitionOrderLoading = false;//关闭忙等框
                                    this.petAcquisitionOrderFormVisible = false;//关闭弹出框
                                })
                        });
                    }
                });
            },
            selsChange: function (sels) {//选中的所有行sels
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id);//[1,2]
                this.$confirm('确认删除选中记录吗？', '温馨提示', {
                    type: 'warning'
                }).then(() => {//返回框的确认按钮
                    this.listLoading = true;
                    //NProgress.start();

                    this.$http.patch("/petAcquisitionOrder",ids)
                        .then(result=>{
                            this.listLoading = false;
                            result = result.data;
                            if(result.success){//删除成功
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.page = 1;//删除成功定位到第一页
                            }else{//后端删除失败
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
                            }
                            this.getPetAcquisitionOrders();
                        })
                        .catch(result=>{
                            this.listLoading = false;
                            this.$message({
                                message: '系统异常',
                                type: 'error'
                            });
                        })
                }).catch(() => {//取消确认框

                });
            },
            info(index, row){
                this.petAcquisitionOrderInfoVisible = true;//显示编辑窗口

                let orderId = row.id;
                this.$http.get("/petAcquisition/"+orderId)
                    .then(result=>{
                        this.petAcquisitionOrderInfo = result.data;
                    })
                    .catch(result=>{

                    })


            }
        },
        mounted() {
            this.getPetAcquisitionOrders();
        }
    }

</script>

<style scoped>

</style>